<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019-10-18
 * Time: 11:06
 */

namespace app\manage\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;

// 引入ZBuilder
use app\common\model\WorkConfig as WorkConfigModel;
use think\Db;

class WorkConfig extends Admin
{
    //打卡配置列表
    public function lists()
    {
        // 读取数据
        $map = $this->getMap();
        // 数据列表
        $data_list = Db::name('qt_work_config')
            ->alias('w')
            ->leftJoin('qt_store s', 'w.store_id = s.id')
            ->field('w.*,s.name as store_name')
            ->where($map)
            ->order('id desc')
            ->paginate();
        // 分页数据
        $page = $data_list->render();
        $btn_access1 = [
            'title' => '编辑配置',
            'icon' => 'fa fa-fw fa-pencil',
            'class' => 'btn btn-xs btn-default',
            'href' => url('edit', ['id' => '__id__']),
        ];
        $btn_access3 = [
            'title' => '新增配置',
            'icon' => 'fa fa-fw fa-plus',
            'class' => 'btn btn-info',
            'href' => url('add'),
        ];
        $groupRes = Db::name('qt_group')->whereIn('pid', ['0', '1'])->order('id asc')->column('id,name');
        //设置页面
        return ZBuilder::make('table')
            ->hideCheckbox()
            ->addColumn('id', '编号', 'text')
            ->addColumn('name', '配置名称', 'text')
            ->addColumn('store_name', '所属门店', 'text')
            ->addColumn('address', '打卡地址', 'text')
            ->addColumn('lon', '经度', 'text')
            ->addColumn('lat', '纬度', 'text')
            ->addColumn('distance', '打卡距离(单位：米)', 'text')
            ->addColumn('status', '状态', 'status', '', ['1' => '显示', '2' => '隐藏'])
            ->addColumn('created_time', '创建时间', 'datetime', '', 'Y-m-d H:i:s')
            ->addColumn('right_button', '操作', 'btn')
            ->setSearchArea([
                ['select:2', 'w.group_id', '所属团队', 'eq', '', $groupRes],
                ['text:2', 'w.name', '配置名称', 'like'],
            ])
            ->addTopButton('single', $btn_access3) // 添加顶部按钮
            ->addRightButton('edit', $btn_access1) // 添加右侧按钮
            ->setPrimaryKey('id') // 设置主键名为username
            ->setColumnWidth([
                'id' => 30,
                'status' => 50,
                'lon' => 80,
                'lat' => 80,
                'right_button' => 50,
                'name' => 100,
                'title' => 60
            ])
            ->setPageTitle('考勤班次')
            ->setPageTips('经纬度不显示的或者显示不正确的，请手动修改配置', 'danger')
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->fetch();
    }

    //添加打卡配置[地址，距离]
    public function add()
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
            $result = $this->validate($data, 'WorkConfig.add');
            if (true !== $result) $this->error($result);
            $data['created_time'] = time();
            if(empty($data['area'])){
                $this->error('请选择省市区');
            }
            $area = Db::name('qt_area')->where('id',$data['area'])->find();
            $city = Db::name('qt_area')->where('id',$area['pid'])->find();
            $province = Db::name('qt_area')->where('id',$city['pid'])->find();
            $data['address'] =$province['name'].$city['name'].$area['name'].$data['address'];
            $url = 'http://restapi.amap.com/v3/geocode/geo?key=363f73cc6d1cd03f815332fc5ed430e9&s=rsv3&city=35&address='.$data['address'];
            $coordinate = json_decode(https_get($url),true);
            if($coordinate['info'] == 'OK'){
                $location = explode(',',$coordinate['geocodes'][0]['location']);
                $data['lat'] = $location[1];
                $data['lon'] = $location[0];
            }
            $find = Db::name('qt_work_config')->where('store_id',$data['store_id'])->find();
            if(empty($find)){
                if (WorkConfigModel::create($data)) {
                    $this->success('新增成功', url('lists'));
                } else {
                    $this->error('新增失败');
                }
            }else{
                $this->error('该团队已经存在打卡设置');
            }

        } else {
            $storeRes = Db::name('qt_store')->where('status','1')->column('id,name');
            return ZBuilder::make('form')
                ->addFormItems(
                    [
                        ['text:7', 'name', '分类名称'],
                        ['select:7', 'store_id', '选择门店', '<code>请选择所属门店</code>', $storeRes],
                        ['linkages', 'area', '请选择地址', '', 'qt_area', '3', '', 'id,name,pid'],
                        ['text:7', 'address', '详细地址'],
                        ['radio:7', 'distance', '打卡距离', '<code>设置打卡距离坐标的距离</code>', ['50' => '50米', '100' => '100米', '150' => '150米', '200' => '200米'], '50'],
                        ['radio:7', 'status', '状态', '', ['1' => '显示', '2' => '隐藏'], '1'],
                    ]
                )
                ->setPageTitle('新增打卡设置')
                ->fetch();
        }
    }

    //编辑打卡配置[地址，距离]
    public function edit($id = null)
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data, 'WorkConfig.add');
            if (true !== $result) $this->error($result);
            if (WorkConfigModel::update($data)) {
                $this->success('编辑成功', 'lists');
            } else {
                $this->error('编辑失败');
            }
        } else {
            $info = WorkConfigModel::get($id);
            $groupRes = Db::name('qt_group')->whereIn('pid', ['0', '1'])->order('id asc')->column('id,name');
            return ZBuilder::make('form')
                ->addFormItems(
                    [
                        ['hidden', 'id', 'id'],
                        ['text:7', 'name', '分类名称'],
                        ['select:7', 'group_id', '选择岗位', '<code>请选择所属团队</code>', $groupRes],
                        ['text:7', 'address', '详细地址'],
                        ['text:7', 'lon', '经度','<code>数字大于100的是经度</code>'],
                        ['text:7', 'lat', '纬度','<code>数字小于100的是纬度</code>'],
                        ['radio:7', 'distance', '打卡距离', '<code>设置打卡距离坐标的距离</code>', ['50' => '50米', '100' => '100米', '150' => '150米', '200' => '200米']],
                        ['radio:7', 'status', '状态', '', ['1' => '显示', '2' => '隐藏'], '1'],
                    ]
                )
                ->setFormData($info)
                ->setPageTips('经纬度查询地址：https://lbs.amap.com/tools/picker', 'danger')
                ->setPageTitle('编辑打卡设置')
                ->fetch();
        }
    }
}